#!/bin/bash

help() {
  echo "Usage:"
  echo "  zmicro plugin install <plugin_name> [plugin_version]"
  echo ""
}

check_plugin() {
  local plugin_name=$1
  local plugin_url="${ZMICRO_PLUGIN_REPO_PREFIX}${plugin_name}"

  local status_code=$(curl -o /dev/null -s -w "%{http_code}\n" $plugin_url)
  if [ "$status_code" != "200" ]; then
    log::error "plugin $plugin_name not found"
    exit 1
  fi
}

core() {
  if [[ $# -eq 0 ]]; then
    help
    exit 0
  fi

  local plugin_name=$1
  local plugin_version=$2
  local plugin_url=$3

  # compatible no version provided, like `zmicro plugin add` command
  #   such as: zmicro install $plugin_name $plugin_url [$plugin_version]
  if [ "$(string::match $plugin_version ^http)" = "true" ] || [ "$(string::match $plugin_version ^git)" = "true" ]; then
    plugin_url=$plugin_version
    plugin_version=$3
  fi

  if [ -z "$plugin_url" ]; then
    # @TODO check github
    if [ "$(net::is_github_visitable)" = "false" ]; then
      export ZMICRO_PLUGIN_GITHUB="https://gitee.com/zmicro-design"
      export ZMICRO_PLUGIN_REPO_PREFIX="$ZMICRO_PLUGIN_GITHUB/plugin-"
    fi

    plugin_url="${ZMICRO_PLUGIN_REPO_PREFIX}${plugin_name}"
  fi

  if [ -z "$plugin_url" ]; then
    check_plugin $plugin_name $plugin_version
  fi

  # echo "[commands][plugin][install] $plugin_name $plugin_url $plugin_version"
  zmicro plugin add $plugin_name $plugin_url $plugin_version
}

run() {
  core $@
}

run $@
